package com.alpha.runes.util;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.method.ReplacementTransformationMethod;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.EditText;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;


/**
 * dp、sp 转换为 px 的工具类
 *
 * @author fxsky 2012.11.12
 */
public class DisplayUtil {
    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale);
    }

    public static String getTime() {

        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳

        String str = String.valueOf(time);

        return str;

    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        int res = 0;
        final float scale = context.getResources().getDisplayMetrics().density;
        if (dpValue < 0)
            res = -(int) (-dpValue * scale + 0.5f);
        else
            res = (int) (dpValue * scale + 0.5f);
        return res;
    }


    public static int getGapMinutes(String startDate, String endDate) {

        long start = Long.parseLong(startDate);

        long end = Long.parseLong(endDate);


        int minutes = (int) ((end - start) / 60);

        return minutes;

    }


    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取当前手机屏幕分辨率，然后根据和设计图的比例对照换算实际字体大小
     *
     * @return
     */
    public static float getFontSize(Context context, int textSize) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        int screenHeight = dm.heightPixels;
        int rate = (int) (textSize * (float) screenHeight / 1920);
        return rate;
    }

    public static String setMoney(double num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.0");
        if (num < 1) {
            result = num + "";
        } else if (num < 1000) {
            result = df.format(num) + "";
        } else if (num >= 1000 && num < 10000) {
            return df.format(num / 1000) + "k";
        } else {
            return df.format(num / 10000) + "w";
        }
        result = result.replace(".0", "");

        return result;
    }


    public static String setTransNum(double num) { // 去小数取整
        String result = "";
        if (num < 1) {
            result = 1 + "";
        } else {
            if (String.valueOf(num).contains(".")) {
                String[] split = String.valueOf(num).split("\\.");      //必须要加\\转义字符，否则返回的split数组是length为0的空数组
                result = split[0];
            }
        }
        return result;
    }

    public static String setCash(double num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.00");
        if (num < 1) {
            result = num + "";
        } else if (num < 10000) {
            result = df.format(num);
        } else if (num >= 10000) {
            result = df.format(num / 10000);
        }

        if (result.startsWith(".")) {
            result = "0" + result;
        }

        return result;
    }


    public static String setYuE(double num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.00");
        if (num < 1) {
            result = num + "";
        } else {
            result = df.format(num) + "";
        }
        return result;
    }

    public static String setYuE(BigDecimal num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.00");
        int a = num.intValue();
        if (a < 1) {
            result = num + "";
        } else {
            result = df.format(num) + "";
        }
        return result;
    }

    public static String setMoney(int num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.0");
        if (num < 1000) {
            result = num + "";
        } else if (num >= 1000 && num < 10000) {
            return num / 1000 + "k";
        } else {
            return num / 10000 + "w";
        }
        return result;
    }

    public static String setMoneyNum(double num) {
        String result = "";
        DecimalFormat df = new DecimalFormat("#.00");
        if (num < 1) {
            result = num + "";
        } else if (num >= 1 && num < 10000) {
            result = df.format(num) + "";
        } else {
            return df.format(num / 10000) + "万";
        }
//        if (String.valueOf(num).endsWith("0")) {
        result = result.replace(".00", "");
//        }

        return result;
    }



    public static void editTextLimit(EditText editText, int number) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                if (source.equals("·") || source.equals("*")) {
                    return null;
                }

                for (int i = start; i < end; i++) {
                    if (!Character.isLetterOrDigit(source.charAt(i))
                            && !Character.toString(source.charAt(i)).equals("_")
                            && !Character.toString(source.charAt(i)).equals("-")) {
                        return "";
                    }
                }

                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                } else {
                    return null;
                }

            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(number)});
    }


    public static void onlyChinese(EditText editText, int lenth) {
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (!isChinese(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(lenth)});
    }


    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }


    public static ReplacementTransformationMethod replacementTransformationMethod = new ReplacementTransformationMethod() {
        @Override
        protected char[] getOriginal() {
            char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return aa;
        }

        @Override
        protected char[] getReplacement() {
            char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return cc;
        }
    };


    /**
     * 千分位 展示钱
     * <p>
     * setMaximumFractionDigits设置最大小数位数
     * setGroupingSize设置分组大小，也就是显示逗号的位置
     * setRoundingMode设置四舍五入的模式
     *
     * @param price
     * @param halfUp
     * @return
     */
    public static String formatPrice(double price, boolean halfUp) {
        DecimalFormat formater = new DecimalFormat();
        // keep 2 decimal places
        formater.setMaximumFractionDigits(2);
        formater.setGroupingSize(3);
        formater.setRoundingMode(halfUp ? RoundingMode.HALF_UP : RoundingMode.FLOOR);
        return formater.format(price);
    }

}